package com.ygqh.baby.service.pay.app.alipay;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ResourceBundle;

import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
import com.alipay.api.DefaultAlipayClient;

public class AlipayAppUtils {

	public final static String charSet = "UTF-8";

	public final static String appid;
	public final static String privatekey;
	public final static String rsa_privatekey;
	public final static String rsa_publickey;

	public final static String publickey;
	public final static String signType;
	public final static String productCode = "QUICK_MSECURITY_PAY";// 销售产品码，商家和支付宝签约的产品码，为固定值QUICK_MSECURITY_PAY
	public final static String serverUrl;

	public final static String payNotifyUrl;
	public final static AlipayClient alipayClient;
	static {
		ResourceBundle WX_BUNDLE = ResourceBundle.getBundle("prop/pay");
		signType = WX_BUNDLE.getString("app.alipay.signType");
		serverUrl = WX_BUNDLE.getString("app.alipay.serverUrl");
		payNotifyUrl = WX_BUNDLE.getString("app.alipay.notifyUrl");
		publickey = WX_BUNDLE.getString("app.alipay.publickey");

		appid = WX_BUNDLE.getString("app.alipay.appid");
		privatekey = WX_BUNDLE.getString("app.alipay.privatekey");
		rsa_privatekey = WX_BUNDLE.getString("app.alipay.RSA.privatekey");
		rsa_publickey = WX_BUNDLE.getString("app.alipay.RSA.publickey");
		alipayClient = new DefaultAlipayClient(serverUrl, appid, rsa_privatekey, "json", "UTF-8", rsa_publickey, signType);
	}

	public static Map<String, String> getParameterMap(Map<String, String[]> requestParams) {
		Map<String, String> params = new HashMap<String, String>();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			/*
			 * valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");
			 */
			params.put(name, valueStr);
		}
		return params;
	}

	public static Boolean checkAppId(String appId) {
		if (appid.equals(appId)) {
			return true;
		}
		return false;

	}

	public static String getResponseMsg(AlipayResponse response) {
		StringBuffer sb = new StringBuffer();
		sb.append(response.getCode()).append(">>").append(response.getMsg()).append(">>>").append(response.getSubCode()).append(">>>")
				.append(response.getSubMsg());
		return sb.toString();
	}

}
